package cn.tianyigps.m7.beans;


import cn.tianyigps.m7.analyze.DataAnalyze;
import cn.tianyigps.m7.command.Command;
import cn.tianyigps.m7.utils.CRCUtil;
import cn.tianyigps.m7.utils.MapObjectUtil;
import cn.tianyigps.m7.utils.MessageCoding;
import io.netty.util.internal.StringUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bson.Document;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * Created with IDEA
 *
 * @description: OBD设备 起始位 7E
 * @author: cui.guibin
 * @create: 2019/3/7 11:16
 **/
public class M7 extends Equipment{

    private  static  Logger log = LogManager.getLogger(M7.class);

    public M7(String equipmentId, String type) {
        super(equipmentId, type);
    }

    @Override
    public boolean checkData(String data) {
        return false;
    }

    public static String getPackType(String data) {

        String head = data.substring(0, 2).toUpperCase();
        String packageType = "";
        if ("78".equals(head)){
            packageType = data.substring(0,4) + data.substring(6,8);
        }else if ("79".equals(head)){
            packageType = data.substring(0,4) + data.substring(8,10);
        }
        return packageType;
    }

    @Override
    public List<Document> analysisPackageType(String strData) {
        if (StringUtil.isNullOrEmpty(strData)) {
            log.error("报文错误：  " + strData);
            return null;
        }
        System.out.println(strData);
        String packType = getPackType(strData);
        int length = strData.length();
        String body = "";
        if (packType.startsWith("7878"))
           body = strData.substring(8, length - 12);//消息内容
        else if(packType.startsWith("7979"))
            body = strData.substring(10, length - 12);//消息内容

        StandardModel standardModel = null;
        switch (packType){
            case "787801": // 登陆包
                standardModel = DataAnalyze.loginAnalyze(body);
                break;
            case "787822": // 定位包
                standardModel = DataAnalyze.locationAnalyze(body);
                break;
            case "787813": // 心跳包
                standardModel = DataAnalyze.heartBeatAnalyze(body);
                break;
            case "787826": // 报警包
                standardModel = DataAnalyze.alarmAnalyze(body);
                break;
            case "787824": // 基站包
                standardModel = DataAnalyze.lbsInfoAnalyze(body);
                break;
            case "797921": // 下发指令回复包
                standardModel = DataAnalyze.analysisReplyPackage(body);
                String content = (String) standardModel.getExtend().get("content");
                Command.instructionReply(this.getEquipmentId(),content,200);
                break;
            case "797994": // iccid包
                standardModel = DataAnalyze.iccidAnalyze(body);
                break;
                default:
        }
        if (!Optional.ofNullable(standardModel).isPresent())
            return null;
        commonFiledsAssign(standardModel,strData);
        standardModel.setEquipmentId(this.getEquipmentId());
        Document basicDBObject = null;
        try {
            basicDBObject = MapObjectUtil.objectToMap(standardModel);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Arrays.asList(basicDBObject);
    }
    private static void commonFiledsAssign(StandardModel model, String str) {
        //所有的m5设备包共有的数据
        model.setEquipmentType("TCP")
                .setStartBit("7878")
                .setProtocolNumber(getPackType(str).substring(4,6))
                .setOriginalData(str)
                .setReportTime(new Date())
                .setPowerType("wired");
    }




    @Override
    public byte[] response(String strData) {
        //获取标识位置
        String packType = getPackType(strData);
        packType = packType.replace("7979", "7878");
        StringBuilder stringBuilder = new StringBuilder();
        //M7设备登陆回复包,校验值为 CRC-16/X25参数模型  参考http://www.ip33.com/crc.html
        if ("787801".equals(packType)) {
            //计算CRC-16/X25参数模型的校验值
            String hexCheck = CRCUtil.CRC_16_X25(MessageCoding.hexStringToBytes("05" + packType.substring(4, 6) + "0001"));
            StringBuilder append = stringBuilder.append("787805").append(packType.substring(4, 6)).append("0001").append(hexCheck).append("0D0A");
            return MessageCoding.hexStringToBytes(append.toString());
        }
        return null;
    }

    @Override
    public byte[] generalResponse(String strData) {
        //获取标识位置
        String packType = getPackType(strData);
        packType = packType.replace("7979", "7878");
        StringBuilder stringBuilder = new StringBuilder();
        //M7设备心跳回复包，校验值为 CRC-16/X25参数模型  参考http://www.ip33.com/crc.html
        if ("787813".equals(packType)) {
            //计算CRC-16/X25参数模型的校验值
            String hexCheck = CRCUtil.CRC_16_X25(MessageCoding.hexStringToBytes("05" + packType.substring(4, 6) + "0001"));
            StringBuilder append = stringBuilder.append("787805").append(packType.substring(4, 6)).append("0001").append(hexCheck).append("0D0A");
            return MessageCoding.hexStringToBytes(append.toString());
        }
        return null;
    }

    @Override
    public byte[] command(String data) {
        // 获取设备值守指令，返回下发
        return new byte[0];
    }

    public static void main(String[] args) {
        M7 m7 = new M7("869115400114969","m7");
        String strData = "78783124130416092E2A0001CC000418C900C42B0018C9003F302518C9003F2E2518C900C42D1C0000000000000000010002174B0D0A";
        m7.analysisPackageType(strData);
    }
}
